package sz.szsmk.citizencard.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;
import com.youzan.androidsdk.YouzanSDK;
import com.youzan.androidsdk.YouzanToken;
import com.youzan.androidsdk.basic.YouzanBrowser;
import com.youzan.androidsdk.event.AbsAuthEvent;
import com.youzan.androidsdk.event.AbsChooserEvent;
import com.youzan.androidsdk.event.AbsShareEvent;
import com.youzan.androidsdk.event.AbsStateEvent;
import com.youzan.androidsdk.model.goods.GoodsShareModel;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.request.YzanRequest;
import sz.szsmk.citizencard.model.network.bean.response.YzanResponse;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.ui.activity.YouzanActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.StringUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/9/10 21:03
 * description:
 */
@Route("youzanfr")
public class YouzanFragment extends WebViewFragment implements SwipeRefreshLayout.OnRefreshListener {
    private YouzanBrowser mView;
    private SwipeRefreshLayout mRefreshLayout;
    private Toolbar mToolbar;
    private NetworkDateSources mNetworkDateSource;
    private YzanResponse mRes;

    public static final String URL = "https://uic.youzan.com/sso/open/initToken";

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case 1:
                    String tokenYouzan = mRes.getAccess_token_youzan();
                    String cookieKey = mRes.getCookie_key();
                    String cookieValue = mRes.getCookie_value();
                    YouzanToken youzanToken = new YouzanToken();
                    youzanToken.setAccessToken(tokenYouzan);
                    youzanToken.setCookieKey(cookieKey);
                    youzanToken.setCookieValue(cookieValue);
                    YouzanSDK.sync(getActivity(), youzanToken);
                    mView.sync(youzanToken);
                    break;

                case 0:

                    break;
                default:
                    break;
            }
        }
    };
    private ImageView backIv;
    private TextView mTitle;

    private String url;
    private LinearLayout mYouzanToolbar;
    private String youzanurl;


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.mNetworkDateSource = NetworkDateSources.getInstance();
//        youzanurl = ACache.get(getActivity()).getAsString("youzanurl");
        String sykt = ACache.get(DaggerApplication.getIns()).getAsString("sykt");
        if (sykt != null && sykt.equals("sykt")) {
            final String youzanurl = getArguments().getString(YouzanActivity.KEY_URL);
            url = youzanurl;
        } else {
            url = "https://j.youzan.com/ofWjHY";
        }
        setupViews(view);
        setupYouzan();
        mView.loadUrl(url);
//        StatusBarUtil.setImmersiveStatusBar(getActivity(), true);
        setPadding(view, R.id.main_layout);
//        mView.loadUrl(url);
    }

    @Override
    protected int attachLayoutRes() {
        return 0;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    public void onResume() {
        super.onResume();

//        ((IMainActivity) getActivity()).getFragment(3);
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void updateViews() {

    }

    public static YouzanFragment getInstance() {
        YouzanFragment homeFragment = new YouzanFragment();
        return homeFragment;
    }

    private void setupViews(View contentView) {
        //WebView
        mView = getWebView();

        mToolbar = (Toolbar) contentView.findViewById(R.id.toolbar);
        mTitle = (TextView) contentView.findViewById(R.id.setting_title);
        backIv = (ImageView) contentView.findViewById(R.id.back);
        mYouzanToolbar = (LinearLayout) contentView.findViewById(R.id.youzan_title);
        boolean goBack = mView.canGoBack();
//        if (!goBack) {
//            backIv.setVisibility(View.GONE);
//        }
        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mView.canGoBack()) {
                    mView.goBack();
                    String title = mView.getTitle();

//                    finish();
                } else {
                    getActivity().onBackPressed();
                }
//                getActivity().finish();
            }
        });
        mRefreshLayout = (SwipeRefreshLayout) contentView.findViewById(R.id.swipe);

        //刷新
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED);
        mRefreshLayout.setEnabled(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ACache.get(DaggerApplication.getIns()).remove("sykt");
    }

    private void setupYouzan() {


        //认证事件, 回调表示: 需要需要新的认证信息传入
        mView.subscribe(new AbsAuthEvent() {

            @Override
            public void call(Context context, boolean needLogin) {
                //伪代码
                login();
                if (needLogin) {

                }
//                if(false){ //判断App内的用户是否登录
//                    //调用login接口, 获取数据, 组装成YouzanToken, 回传给 mView.sync()
//
//                } else if (false){
//                    /*Intent intent = new Intent(YouzanActivity.this, LoginActivity.class);
//                    startActivityForResult(intent, REQUEST_CODE_LOGIN);*/
//                } else {
//
//                    //调用initToken接口, 获取数据, 组装成YouzanToken, 回传给 mView.sync()
//
//                }
            }
        });

        //文件选择事件, 回调表示: 发起文件选择. (如果app内使用的是系统默认的文件选择器, 该事件可以直接删除)
        mView.subscribe(new AbsChooserEvent() {
            @Override
            public void call(Context context, Intent intent, int requestCode) throws ActivityNotFoundException {
                startActivityForResult(intent, requestCode);
            }
        });

        //页面状态事件, 回调表示: 页面加载完成
        mView.subscribe(new AbsStateEvent() {
            @Override
            public void call(Context context) {
                String sykt = ACache.get(DaggerApplication.getIns()).getAsString("sykt");
                if (sykt != null && sykt.equals("sykt")) {
                    mTitle.setText(mView.getTitle());
                } else {
                    mTitle.setText(mView.getTitle());
                }
                String yzUrl = mView.getUrl();
                if (!StringUtils.isBlank(yzUrl)) {
                    if (yzUrl.contains("home")) {
                        backIv.setVisibility(View.VISIBLE);
                    } else {
                        backIv.setVisibility(View.VISIBLE);
                    }
                }
                L.e(Constant.TAG, "有赞首页URL--" + url);
                mRefreshLayout.setRefreshing(false);
                mRefreshLayout.setEnabled(true);

            }
        });

        //分享事件, 回调表示: 获取到当前页面的分享信息数据
        mView.subscribe(new AbsShareEvent() {
            @Override
            public void call(Context context, GoodsShareModel data) {
                /**
                 * 在获取数据后, 可以使用其他分享SDK来提高分享体验.
                 * 这里调用系统分享来简单演示分享的过程.
                 */
                String content = data.getDesc() + data.getLink();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, content);
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, data.getTitle());
                sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            }
        });

    }


    private void login() {
        YzanRequest yzanRequest = new YzanRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        yzanRequest.setAccess_token(access_token);
        String json = new Gson().toJson(yzanRequest);

        L.e(Constant.TAG, "loginYzan====》请求" + json);
        mNetworkDateSource.loginYzan(yzanRequest, new SubscribeResult<YzanResponse>() {
            @Override
            protected void onOk(YzanResponse response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "loginYzan====》响应" + json);
                mRes = response;
                if (mRes != null) {
                    handler.sendEmptyMessage(1);
                }

            }

            @Override
            protected void onFailure(YzanResponse response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }


    @Override
    protected int getWebViewId() {
        //YouzanBrowser在布局文件中的id
        return R.id.view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        ACache.get(DaggerApplication.getIns()).remove("sykt");
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected int getLayoutId() {
        //布局文件
        return R.layout.fragment_youzan;
    }

    @Override
    public boolean onBackPressed() {
        //页面回退
        return getWebView().pageGoBack();
    }

    @Override
    public void onRefresh() {
        //重新加载页面
        mView.reload();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            //另需处理认证等...

            mView.receiveFile(requestCode, data);
        }
    }

    protected void setPadding(View view, @IdRes int idResource) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                ViewGroup drawerRoot = (ViewGroup) view.findViewById(idResource);
                int result = 0;
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
                if (resourceId > 0) {
                    result = getResources().getDimensionPixelSize(resourceId);
                }
                drawerRoot.setPadding(drawerRoot.getPaddingLeft(),
//                        result,
                        0,
                        drawerRoot.getPaddingRight(),
                        drawerRoot.getBottom());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}